﻿using System.Collections.ObjectModel;
using System.Windows.Input;
using IS_Ever_Green.DataAccess.Model;
using IS_Ever_Green.DataAccess.Model.Repositories;

namespace IS_Ever_Green.ViewModel
{
    public class EmployeeViewModel : BaseViewModel
    {
        private ObservableCollection<UserModel> _employeesList;
        private UserModel _selectedEmployee;
        private UserModel _newEmployee = new UserModel();
        private IUserRepository userRepository;

        public ObservableCollection<UserModel> EmployeesList
        {
            get { return _employeesList; }
            set
            {
                _employeesList = value;
                OnPropertyChanged(nameof(EmployeesList));
            }
        }

        public UserModel SelectedEmployee
        {
            get { return _selectedEmployee; }
            set
            {
                _selectedEmployee = value;
                OnPropertyChanged(nameof(SelectedEmployee));
            }
        }

        public UserModel NewEmployee
        {
            get { return _newEmployee; }
            set
            {
                _newEmployee = value;
                OnPropertyChanged(nameof(NewEmployee));
            }
        }

        public ICommand AddCommand {  get; private set; }
        public ICommand EditCommand { get; private set; }
        public ICommand DeleteCommand { get; private set; }

        public EmployeeViewModel()
        {
            userRepository = new UserRepository();
            FillEmployeesFromRepository();
            AddCommand = new CommandViewModel(AddEmployee);
            EditCommand = new CommandViewModel(EditEmployee);
            DeleteCommand = new CommandViewModel(DeleteEmployee);
        }

        private void FillEmployeesFromRepository()
        {
            var employeesFromRepo = userRepository.GetEmployeesWithRole("Employee");
            EmployeesList = new ObservableCollection<UserModel>(employeesFromRepo);
        }

        private void AddEmployee(object obj)
        {
            if (!userRepository.UserExists(NewEmployee.LoginUser))
            {
                NewEmployee.RoleId = 3;

                userRepository.RegisterUser(NewEmployee);
            }
        }

        private void EditEmployee(object obj)
        {
            if (SelectedEmployee != null)
            {
                userRepository.EditUser(SelectedEmployee);
            }
        }

        private void DeleteEmployee(object obj)
        {
            if (SelectedEmployee != null)
            {
                userRepository.DeleteUser(SelectedEmployee);
                EmployeesList.Remove(SelectedEmployee);
            }
        }
    }
}
